package org.dut.community.controller;

import org.dut.community.entity.Comment;
import org.dut.community.entity.Event;
import org.dut.community.event.EventProducer;
import org.dut.community.service.CommentService;
import org.dut.community.service.DiscussPostService;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.HostHolder;
import org.dut.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;



@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {
    @Autowired
    private CommentService commentService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/add/{discussPostId}",method = RequestMethod.POST)
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);

        // 系统通知 评论帖子
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            Event event = Event.builder()
                        .topic(TOPIC_COMMENT)
                        .userId(hostHolder.getUser().getId())
                        .entityType(comment.getEntityType())
                        .entityId(discussPostId)
                        .build();
            eventProducer.fireEvent(event);
            // 评论帖子 增加分数
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, discussPostId);
        }


        return "redirect:/discuss/detail/" + discussPostId;
    }
}
